<?php

namespace Icsoc\SecurityBundle\Controller;

use Icsoc\ReportBundle\Controller\ReportController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * 角色管理
 * Class RoleController
 * @package Icsoc\SecurityBundle\Controller
 */
class RoleController extends ReportController
{
    /** @var array 单独添加的角色 */
    private $addRole = array(
        '1'=>array(
            array('menuUrl'=>'icsoc_agent_add', 'menuText'=>'新建坐席'),
            array('menuUrl'=>'icsoc_agent_edit', 'menuText'=>'编辑坐席'),
            array('menuUrl'=>'icsoc_agent_del', 'menuText'=>'删除坐席'),
            array('menuUrl'=>'icsoc_queue_batch', 'menuText'=>'技能组批量新建'),
            array('menuUrl'=>'icsoc_queue_agqu_index', 'menuText'=>'技能组分配'),
            array('menuUrl'=>'icsoc_agent_login', 'menuText'=>'坐席切换'),
            array('menuUrl'=>'icsoc_agent_login_enter', 'menuText'=>'静态坐席登录'),
            array('menuUrl'=>'icsoc_agent_login_edit', 'menuText'=>'静态坐席修改'),
        ),
        '37'=>array(
            array('menuUrl'=>'icsoc_security_setting', 'menuText'=>'参数设置'),
            array('menuUrl'=>'icsoc_show_cus_phone', 'menuText'=>'查看客户号码'),
        ),
        '89'=>array(
            /*array('menuUrl'=>'icsoc_recording_list_batch_down_data', 'menuText'=>'录音导出'),*/
            array('menuUrl'=>'icsoc_recording_list_listen_sound', 'menuText'=>'录音收听'),
            array('menuUrl'=>'icsoc_recording_list_down_sound', 'menuText'=>'录音下载'),
        ),
    );

    private $connNum = array(5, 10, 15, 20, 30);
    private $lostNum = array(10, 20, 25, 30, 35, 40);

    /** @var array 默认颜色 */
    private $defalurColors = array(
        '#007354', '#8dba23', '#674d95', '#41a396', '#d03672',
        '#2a4f85', '#5b98ce', '#6984b3', '#6984b3', '#034968',
        '#6486b3', '#014b68', '#67ab19', '#2c3b4d', '#674690',
        '#636a70', '#d3434d', '#665a88', '#02a2b0', '#294258',
        '#972257', '#d76777', '#613889', '#d3434d', '#e38e01',
        '#872b36', '#2aabaa', '#d03124', '#613886', '#c3268b',
        '#926139', '#e1d46b', '#64555c', '#eeab77', '#585c45',
        '#441a24', '#a88755', '#653f33', '#3b3e1f', '#e28f28',
        '#c77203', '#352b22', '#668740', '#482714', '#455161',
        '#2a4f85', '#5b98ce', '#2e3b4e', '#6984b3', '#45a889',
    );

    /**
     * 坐席状态
     *
     * @var array
     */

    private $agentState = array (
        'ready'=>array('text'=>'就绪', 'background'=>'#6db651'),
        'busy'=>array('text'=>'置忙', 'background'=>'#c44b4b'),
        'ring'=>array('text'=>'振铃', 'background'=>'#e96625'),
        'call'=>array('text'=>'通话', 'background'=>'#37a8e3'),
        'rest'=>array('text'=>'事后处理', 'background'=>'#bd47db'),
    );

    /** @var array 坐席状态置忙原因样式 */
    private $colorExtensionColor = array('#c44b4b', '#a92b2b', '#b63838', '#c23f29', '#d35a45', '#db4780');

    /** @var int 默认字体 */
    private $defautFontSize = 26;

    /** @var string 默认字体颜色 */
    private $defautFontColor = '#ffffff';

    /** @var string 默认背景颜色 */
    private $defautBackground = '#449d44';

    /** @var array $itemType 指标类型 */
    private $itemType = array(
        1 => 'system',
        2 => 'queue',
        3 => 'group',
    );

    /** @var array 需要设置参数的指标 */
    private $paramsSettingItems = array(
        'validSecs'=>array('validConnTotalNum', 'inboundValidConnTotalNum', 'outboundValidConnTotalNum'),
        'xsecs'=>array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'),
    );
    /**
     * 角色管理中不需要再出现的路由
     * @var array
     */
    private $filterUrl = array(
        'icsoc_security_develop_download_work_index',
    );

    /**
     * 角色管理
     * @return Response
     */
    public function roleInfoAction()
    {
        $vccId = $this->getVccId();
        $roles = $this->getDoctrine()->getRepository('IcsocSecurityBundle:CcRoles')->findBy(array('vccId'=>$vccId));
//        $actionList = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcods")
//            ->find($vccId)->getActionList();
//        $userAction = $this->getActionList();
       // $actions = $actionList ? explode(",", $actionList) : array();
        //$userActions = $userAction != 'all' ? explode(",", $userAction) : array('all');
//        $menuList = $this->getDoctrine()->getRepository("IcsocMenuBundle:Menu")
//            ->getMenuList($vccId, $this->container, $actions, $userActions);
        $roleGrade = $this->container->getParameter('role_grade');
//        foreach ($this->addRole as $key => $val) {
//            foreach ($val as $mkey => $menu) {
//                if (!in_array($menu['menuUrl'], $actions)
//                    || (!in_array('all', $userActions) && !in_array($menu['menuUrl'], $userActions))) {
//                    unset($this->addRole[$key][$mkey]);
//                }
//            }
//        }

        return $this->render(
            "IcsocSecurityBundle:Role:roleIndex.html.twig",
            array(
                'roles'=>$roles,
                'roleGrade'=>$roleGrade,
//                'menuList'=>$menuList,
//                'addRole'=>$this->addRole,
            )
        );
    }

    /**
     * 加载数据权限信息
     *
     * @param Request $request
     * @return Response
     */
    public function roleLoadDataAuthorityAction(Request $request)
    {
        $vccId = $this->getVccId();
        $userType = 0;
        $userQueues = array();
        $userGroups = array();
        $roleGrade = $this->getUser()->getRoleGrade();
        $selectDataRole =  $this->container->getParameter('select_data_role');
        $dataRole = $this->container->get("icsoc_core.common.class")->getUserTypes($selectDataRole, $roleGrade);
        $roleId = $request->get('roleId', '');
        $res = $this->container->get('icsoc_data.model.role')->getDataAuthority($roleId);
        if (isset($res['code']) && $res['code'] == 200) {
            $userType = isset($res['data']['user_type']) ? $res['data']['user_type'] : 0;
            if (isset($res['data']['user_queues'])) {
                $userQueues = !empty($res['data']['user_queues']) ? explode(",", $res['data']['user_queues']) : array();
            }
        }
        if ($userType == 3) {
            $userGroups = $userQueues;
            $userQueues = array();
        }

        $queues = $this->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($vccId, true, true);
        $groups = $this->getDoctrine()->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);

        /** @var Boolean $isEnableGroup 是否启用业务组 */
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($vccId);

        return $this->render(
            "IcsocSecurityBundle:Role:roleData.html.twig",
            array(
                'dataRole' => $dataRole,
                'userType' => $userType,
                'queues' => $queues,
                'groups' => $groups,
                'userQueues' => $userQueues,
                'userGroups' => $userGroups,
                'isEnableGroup' => $isEnableGroup,
                'roleGrade' => $roleGrade,
            )
        );
    }

    /**
     * 保存数据权限配置
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function roleSaveDataAuthorityAction(Request $request)
    {
        $roleId = $request->get('roleId', '');
        $dataInfo = $request->get('data_info', '');

        $res = $this->container->get('icsoc_data.model.role')->setDataAuthority(
            array(
                'vcc_code'=>$this->getVccCode(),
                'role_id'=>$roleId,
                'data_info'=>$dataInfo,
            )
        );

        return new JsonResponse($res);
    }

    /**
     * 加载不同配置页面信息
     *
     * @param Request $request
     * @return Response
     */
    public function roleLoadAction(Request $request)
    {
        $tabType = $request->get('tab_type', '');
        $roleId = $request->get('roleId', '');

        $vccId = $this->getVccId();
        //$roles = $this->getDoctrine()->getRepository('IcsocSecurityBundle:CcRoles')->findBy(array('vccId'=>$vccId));
        $actionList = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcods")
            ->find($vccId)->getActionList();
        $userAction = $this->getActionList();
        $actions = $actionList ? explode(",", $actionList) : array();
        $userActions = $userAction != 'all' ? explode(",", $userAction) : array('all');

        switch ($tabType) {
            case 'menus':
                //过滤已经配置的且不再需要的路由
                foreach ($this->filterUrl as $val) {
                    if ($key = array_search($val, $actions)) {
                        unset($actions[$key]);
                    }
                }
                $menuList = $this->getDoctrine()->getRepository("IcsocMenuBundle:Menu")
                    ->getMenuList($vccId, $this->container, $actions, $userActions);

                return $this->render(
                    "IcsocSecurityBundle:Role:roleMenus.html.twig",
                    array(
                        'menuList'=>$menuList,
                        'addRole'=>$this->addRole,
                    )
                );
                break;
            case 'report':
                $conn = $this->get('doctrine.dbal.default_connection');
                $customItems = array();

                /** 处理置忙原因 */
                $result = $conn->fetchAll(
                    "SELECT id,stat_reason FROM win_agstat_reason WHERE vcc_id = :vcc_id",
                    array('vcc_id' => $this->getVccId())
                );

                $reason = array();
                foreach ($result as $v) {
                    $reason['agstanum'.$v['id']] = array('text' => sprintf('%s次数', $v['stat_reason']));
                    $reason['agstaduration'.$v['id']] = array('text' => sprintf('%s时长', $v['stat_reason']));
                }

                if (!empty($result)) {
                    $reason['agstanum_other'] = array('text' => '其他示忙次数');
                    $reason['agstaduration_other'] = array('text' => '其他示忙时长');
                }

                $agentRes = array_merge($this->reportItems['agent']['fixed_report'], $reason);
                $groupRes = array_merge($this->reportItems['group']['fixed_report'], $reason);
                $this->reportItems['agent']['fixed_report'] = $agentRes;
                $this->reportItems['group']['fixed_report'] = $groupRes;

                $connNums = array();
                $connNumscalculateItems = array();

                foreach ($this->connNum as $connNum) {
                    $connNums['conn'.$connNum.'_num'] = array('text' => sprintf('%s秒接通量', $connNum), 'field' => 'conn'.$connNum.'_num');
                    $connNums['conn'.$connNum.'_rate'] = array('text' => sprintf('%s秒接通率', $connNum));
                    $connNumscalculateItems['conn'.$connNum.'_rate'] = array(
                        'numerator' => array(
                            'plus'=> array('conn'.$connNum.'_num'),
                        ),
                        'denominator' => array(
                            'plus'=> array('inboundConnNum'),
                        ),
                        'percent' => 1,
                        'editable' => true,
                    );
                }

                $lostNums = array();
                foreach ($this->lostNum as $lostNum) {
                    $lostNums['lost'.$lostNum.'_num'] = array('text' => sprintf('%s秒放弃量', $lostNum));
                    $lostNums['lost'.$lostNum.'_rate'] = array('text' => sprintf('%s秒放弃率', $lostNum));
                    $connNumscalculateItems['lost'.$lostNum.'_rate'] = array(
                        'numerator' => array(
                            'plus'=> array('lost'.$lostNum.'_num'),
                        ),
                        'denominator' => array(
                            'plus'=> array('inboundConnNum'),
                        ),
                        'percent' => 1,
                        'editable' => true,
                    );
                }

                $this->reportItems['system']['fixed_report'] = array_merge($this->reportItems['system']['fixed_report'], $connNums);
                $this->reportItems['queue']['fixed_report'] = array_merge($this->reportItems['queue']['fixed_report'], $connNums, $lostNums);
                $this->calculateItems['system'] = array_merge($this->calculateItems['system'], $connNumscalculateItems);
                $this->calculateItems['queue'] = array_merge($this->calculateItems['queue'], $connNumscalculateItems);

                /** @var Boolean $isEnableGroup 是否启用业务组 */
                $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($this->getVccId());

                /** 未启用业务组去掉业务组的指标配置 */
                if (empty($isEnableGroup)) {
                    unset($this->reportItems['group']);
                }

                $showValues = array();
                if (!empty($roleId)) {
                    $reportConfigs = $conn->fetchColumn(
                        'SELECT report_config FROM cc_roles WHERE role_id = :role_id',
                        array('role_id' => $roleId)
                    );

                    $globalConfig = $conn->fetchColumn(
                        'SELECT report_config FROM cc_global_report_config WHERE vcc_id = :vcc_id',
                        array('vcc_id' => $this->getVccId())
                    );
                    if (empty($reportConfigs) && !empty($globalConfig)) {
                        $reportConfigs = $globalConfig;
                    }
                    if (!empty($reportConfigs)) {
                        $reportConfigs = json_decode($reportConfigs, true);
                        foreach ($reportConfigs as $items => $reportConfig) {
                            /** 添加自定义指标到报表指标项中 */
                            /*foreach ($reportConfig['customItems'] as $item => $value) {
                                $this->reportItems[$items]['custom_report'][$item] = array('text' => $value, 'custom'=>true);
                            }*/

                            $lastShowValues = array('fixed' => array(),'custom' => array());
                            if (isset($reportConfig['showValues'])) {
                                $lastShowValues = $reportConfig['showValues'];
                            }

                            foreach ($reportConfig['customItems'] as $type => $customItem) {
                                if (!in_array($type, array('fixed', 'custom'))) {
                                    $this->reportItems[$items]['custom_report'][$type] = array('text' => $customItem, 'custom' => true);
                                } else {
                                    foreach ( $customItem as $item => $value) {
                                        $this->reportItems[$items][$type.'_report'][$item] = array(
                                            'custom' => true,
                                            'checked' => false,
                                            'calculate' => true
                                        );
                                    }
                                }
                            }
                            $showValues[$items] = $lastShowValues;

                            if (is_array($reportConfig['calculateItems'])) {
                                foreach ($reportConfig['calculateItems'] as $calculate => $calculateItems) {
                                    if (!empty($calculateItems['numerator']['plus']) || !empty($calculateItems['numerator']['minus']) ||
                                        !empty($calculateItems['numerator']['multiply']['plus']) || !empty($calculateItems['numerator']['multiply']['minus'])) {
                                        $this->calculateItems[$items][$calculate]['numerator'] = $calculateItems['numerator'];
                                        $this->calculateItems[$items][$calculate]['editable'] = true;
                                    }

                                    if (!empty($calculateItems['denominator']['plus']) || !empty($calculateItems['denominator']['minus']) ||
                                        !empty($calculateItems['denominator']['multiply']['plus']) || !empty($calculateItems['denominator']['multiply']['minus'])
                                    ) {
                                        $this->calculateItems[$items][$calculate]['denominator'] = $calculateItems['denominator'];
                                        $this->calculateItems[$items][$calculate]['editable'] = true;
                                    }

                                    if (isset($calculateItems['percent']) && $calculateItems['percent'] == true) {
                                        $this->calculateItems[$items][$calculate]['percent'] = 1;
                                    } else {
                                        $this->calculateItems[$items][$calculate]['percent'] = 0;
                                    }
                                }
                            }

                            $customItems[$items] = $reportConfig['customItems'];
                        }
                    }
                }

                $translator = $this->get('translator');

                /** 处理指标是否选中、是否可编辑 */
                $items = array();
                $originItems = array();
                foreach ($this->reportItems as $key => $reportItems) {
                    foreach ($reportItems as $ke => $reportItem) {
                        foreach ($reportItem as $k => $item) {

                            /** 若配置中存在显示值，则显示配置中的值，否则显示默认值*/
                            if (!empty($showValues[$key][str_replace('_report', '', $ke)])) {
                                foreach( $showValues[$key][str_replace('_report', '', $ke)] as $index => $config) {
                                    if ( $index == $k) {
                                        /** 添加配置显示值*/
                                        $this->reportItems[$key][$ke][$k]['showValue'] = $config['name'];
                                        /** 添加排序值*/
                                        $this->reportItems[$key][$ke][$k]['sort'] = $config['sort'];
                                        /** 添加全局配置*/
                                        $this->reportItems[$key][$ke][$k]['globalConfig'] = $config['globalConfig'];
                                    }
                                }
                            }

                            $originItems[$key][str_replace('_report', '', $ke)][$k]['normalCalculate'] = 1;
                            $this->reportItems[$key][$ke][$k]['normalCalculate'] = 1;
                            /** 指标存在默认计算项，并且editable = true */
                            if (isset($this->calculateItems[$key]) &&
                                in_array($k, array_keys($this->calculateItems[$key])) &&
                                isset($this->calculateItems[$key][$k]['editable']) &&
                                $this->calculateItems[$key][$k]['editable'] == true
                            ) {
                                $this->reportItems[$key][$ke][$k]['calculate'] = true;
                                $originItems[$key][str_replace('_report', '', $ke)][$k]['normalCalculate'] = 2;
                                $this->reportItems[$key][$ke][$k]['normalCalculate'] = 2;
                            }
                            if (isset($reportConfigs[$key][str_replace('_report', '', $ke)]) && in_array($k, $reportConfigs[$key][str_replace('_report', '', $ke)])) {
                                $this->reportItems[$key][$ke][$k]['checked'] = true;
                            }

                            if (isset($this->reportItems[$key][$ke][$k]['showValue'])) {
                                $items[$key][str_replace('_report', '', $ke)][$k] = $this->reportItems[$key][$ke][$k]['showValue'];
                            } else {
                                $items[$key][str_replace('_report', '', $ke)][$k] = $translator->trans($item['text']);
                            }
                        }
                    }
                }

                /** 按照配置排序*/
                foreach ($this->reportItems as $reportType => $reportItems) {
                    foreach($reportItems as $type => $reportItem) {
                        $newReportItem  = $this->container->get('icsoc_data.model.role')->getReportConfigOrder($reportItem, 100);
                        $this->reportItems[$reportType][$type] = $newReportItem;
                    }
                }

                return $this->render(
                    "IcsocSecurityBundle:Role:roleReportConfig.html.twig",
                    array(
                        'items' => json_encode($items),
                        'originItems' => json_encode($originItems),
                        'reportItems' => $this->reportItems,
                        'calculateItems' => json_encode($this->calculateItems),
                        'customItems' => $customItems,
                        'time' => date('ymdHis'),
                    )
                );
                break;
        }
    }

    /**
     * 加载监控配置信息
     *
     * @param Request $request
     * @return Response
     */
    public function roleLoadMonitorConfigAction(Request $request)
    {
        $conn = $this->get('doctrine.dbal.default_connection');

        $roleId = $request->get('roleId', '');
        $vccId = $this->getVccId();

        $translator = $this->get("translator");
        $screenMonitor = $translator->trans('Screen monitor');

        $phones = $this->get("icsoc_data.model.role")->getPhonesByVccId($vccId);

        $mainFields = array();

        /** @var Boolean $isEnableGroup 是否启用业务组 */
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($this->getVccId());

        /** @var string $reportConfigs 报表配置信息 */
        $reportConfigs = $conn->fetchAssoc(
            'SELECT user_type FROM cc_roles WHERE role_id = :role_id',
            array('role_id'=>$roleId)
        );

        /** @var  array $monitorItmeSources 处理需要配置的指标 */
        $monitorItmeSources = array();
        foreach ($this->monitorItems as $key => $reportItems) {
            if (!in_array($key, array('system', 'queue', 'group'))) {
                continue;
            }

            /** 未启用业务组去掉业务组的指标配置 */
            if ($key == 'group' && (empty($isEnableGroup) || $reportConfigs['user_type'] == 1)) {
                continue;
            }

            if (isset($reportItems['monitor_config'])) {
                foreach ($reportItems['monitor_config'] as $k => $reportItem) {
                    if (isset($reportItem['monitor']) && $reportItem['monitor'] == true) {
                        $monitorItmeSources[$key][$k] = $reportItem;
                    }
                }
            }
        }
        if ($reportConfigs['user_type'] == 3) {
            unset($monitorItmeSources['queue']);
        }

        $monitorItems = array();
        //按照system、queue、group排序
        $targetSort = array('system', 'queue', 'group');
        foreach ($targetSort as $target) {
            if (!empty($monitorItmeSources[$target])) {
                $monitorItems[$target] = $monitorItmeSources[$target];
            }
        }

        /** @var array $agentStaReasons 坐席具体置忙原因 */
        $agentStaReasons = $this->get('icsoc_data.model.report')->getAgentStaReason($this->getVccId());
        $reasonIds = array_keys($agentStaReasons);

        /** @var array $agent 坐席默认配置 */
        $agent = array('is_show'=>1, 'type'=>1);
        $agentFields = array();
        $ifFasreason = 0;
        foreach ($this->agentState as $key => $agentSta) {
            if ($key == 'busy' && !empty($agentStaReasons)) {
                $ifFasreason = 1;
                $agentStaReasons[2] = '系统置忙';
                $i = 0;
                foreach ($agentStaReasons as $k => $agentStaReason) {
                    $reason = array(
                        'id'=>$k,
                        'name'=>$agentStaReason,
                        'style'=>array(
                            'background' => $this->colorExtensionColor[$i],
                            'fontSize' => '14px',
                            'fontColor' => $this->defautFontColor,
                        ),
                        'threshold'=>0,
                    );
                    $agent[$key]['if_hasreason'] = $ifFasreason;
                    $agent[$key]['busy_data'][$k] = $reason;
                    $agentFields[$key][$k] = $agentStaReason;
                    $i++;
                }
            } else {
                $agent[$key]['background'] = $agentSta['background'];
                $agent[$key]['fontSize'] = '14px';
                $agent[$key]['fontColor'] = $this->defautFontColor;
                $agent[$key]['threshold'] = 0;
                $agentFields[$key] = $agentSta['text'];
            }
        }

        $items = array();

        $mainField = array();
        $i = 0;
        foreach ($monitorItems as $key => $monitorItmeSource) {
            foreach ($monitorItmeSource as $k => $item) {
                $i = isset($this->defalurColors[$i]) ? $i : 0;
                $mainField[$key][$k]['id'] = $k;
                $mainField[$key][$k]['name'] = $translator->trans($item['text']);
                if (in_array($k, $this->paramsSettingItems['validSecs']) || in_array($k, $this->paramsSettingItems['xsecs'])) {
                    $mainField[$key][$k]['fieldType'] = 1;
                } else {
                    $mainField[$key][$k]['fieldType'] = 0;
                }
                $mainField[$key][$k]['style']['background'] = $this->defalurColors[$i];
                $mainField[$key][$k]['style']['fontSize'] = $this->defautFontSize.'px';
                $mainField[$key][$k]['style']['fontColor'] = $this->defautFontColor;
                $i++;
            }
        }
        $monitorConfigs = $conn->fetchAll(
            'SELECT id,screen_info FROM cc_monitor_screen WHERE role_id = :role_id',
            array('role_id'=>$roleId)
        );

        if (!empty($monitorConfigs)) {
            foreach ($monitorConfigs as $v => $monitorConfig) {
                $monitorConfigScreen = json_decode($monitorConfig['screen_info'], true);

                $dataConfig = array();
                foreach ($monitorConfigScreen['mainFields'] as $key => $configs) {
                    $itemType = $this->itemType[$configs['type']];
                    foreach ($configs['fields'] as $k => $config) {
                        $dataConfig[$itemType][$config['id']] = $config;
                    }
                }

                $configItems = array();
                $i = 0;
                foreach ($monitorItems as $key => $monitorItmeSource) {
                    foreach ($monitorItmeSource as $k => $item) {
                        $i = isset($this->defalurColors[$i]) ? $i : 0;
                        $configItems[$key]['fields'][$k]['text'] = $item['text'];
                        if (isset($dataConfig[$key]) && in_array($k, array_keys($dataConfig[$key]))) {
                            $configItems[$key]['fields'][$k]['checked'] = true;
                            $configItems[$key]['is_show'] = true;
                        } else {
                            $configItems[$key]['fields'][$k]['checked'] = false;
                        }

                        $mainFields['monitorConfigItem'.$v][$key][$k]['id'] = $k;
                        $mainFields['monitorConfigItem'.$v][$key][$k]['name'] = $translator->trans($item['text']);
                        if (in_array($k, $this->paramsSettingItems['validSecs']) || in_array($k, $this->paramsSettingItems['xsecs'])) {
                            $mainFields['monitorConfigItem'.$v][$key][$k]['fieldType'] = 1;
                        } else {
                            $mainFields['monitorConfigItem'.$v][$key][$k]['fieldType'] = 0;
                        }

                        if (isset($dataConfig[$key][$k]['params'])) {
                            $mainFields['monitorConfigItem'.$v][$key][$k]['params'] = $dataConfig[$key][$k]['params'];
                        }

                        if (isset($dataConfig[$key][$k]['paramName'])) {
                            $mainFields['monitorConfigItem'.$v][$key][$k]['paramName'] = $dataConfig[$key][$k]['paramName'];
                        }

                        if (isset($dataConfig[$key][$k]['style'])) {
                            if (empty($dataConfig[$key][$k]['style']['background'])) {
                                $dataConfig[$key][$k]['style']['background'] = $this->defalurColors[$i];
                            }
                            if (empty($dataConfig[$key][$k]['style']['fontColor'])) {
                                $dataConfig[$key][$k]['style']['fontColor'] = $this->defautFontColor;
                            }
                            if (empty($dataConfig[$key][$k]['style']['fontSize'])) {
                                $dataConfig[$key][$k]['style']['fontSize'] = $this->defautFontSize.'px';
                            }
                            $mainFields['monitorConfigItem'.$v][$key][$k]['style'] = $dataConfig[$key][$k]['style'];
                        } else {
                            $mainFields['monitorConfigItem'.$v][$key][$k]['style']['background'] = $this->defalurColors[$i];
                            $mainFields['monitorConfigItem'.$v][$key][$k]['style']['fontSize'] = $this->defautFontSize.'px';
                            $mainFields['monitorConfigItem'.$v][$key][$k]['style']['fontColor'] = $this->defautFontColor;
                        }

                        if (isset($dataConfig[$key][$k]['phones'])) {
                            $mainFields['monitorConfigItem'.$v][$key][$k]['phones'] = $dataConfig[$key][$k]['phones'];
                        } else {
                            $mainFields['monitorConfigItem'.$v][$key][$k]['phones'] = "";
                        }

                        $i++;
                    }
                }

                $items['monitorConfigItem'.$v]['mainFields'] = $configItems;
                $items['monitorConfigItem'.$v]['agent']['fields'] = $agentFields;
                $items['monitorConfigItem'.$v]['agent']['is_show'] =
                    isset($monitorConfigScreen['agent']['is_show']) && $monitorConfigScreen['agent']['is_show'] == 1 ? true : false;
                $items['monitorConfigItem'.$v]['agent']['is_group_show'] =
                    isset($monitorConfigScreen['agent']['is_group_show']) && $monitorConfigScreen['agent']['is_group_show'] == 1 ? true : false;
                $items['monitorConfigItem'.$v]['agent']['type'] =
                    isset($monitorConfigScreen['agent']['type']) ? $monitorConfigScreen['agent']['type'] : 1;

                $items['monitorConfigItem'.$v]['name'] =
                    isset($monitorConfigScreen['name']) ? $monitorConfigScreen['name'] : $screenMonitor;
                $items['monitorConfigItem'.$v]['refresh'] =
                    isset($monitorConfigScreen['refresh']) ? $monitorConfigScreen['refresh'] : "10";
                $items['monitorConfigItem'.$v]['id'] = $monitorConfig['id'];

                if (!empty($monitorConfigScreen['agent']['ready'])) {
                    //对agent下面的每一个进行遍历
                    $nowReasonIds = array();
                    foreach ($monitorConfigScreen['agent'] as $agentk => $agentv) {
                        //先判断$agentk是否是busy，并且有置忙原因
                        if ($agentk == 'busy') {
                            if (isset($monitorConfigScreen['agent']['busy']['busy_data'])) {
                                $agents['monitorConfigItem'.$v]['busy']['if_hasreason'] = 1;
                            } else {
                                $agents['monitorConfigItem'.$v]['busy']['if_hasreason'] = 0;
                            }
                            if (!empty($monitorConfigScreen['agent']['busy']['busy_data']) && is_array($monitorConfigScreen['agent']['busy']['busy_data'])) {
                                foreach ($monitorConfigScreen['agent']['busy']['busy_data'] as $value) {
                                    if (!isset($value['threshold'])) {
                                        $value['threshold'] = 0;
                                    }
                                    $agents['monitorConfigItem'.$v]['busy']['busy_data'][$value['id']] = $value;
                                    $nowReasonIds[] = $value['id'];
                                }
                            }
                        } else {
                            if (is_array($agentv)) {
                                if (!isset($agentv['threshold'])) {
                                    $monitorConfigScreen['agent'][$agentk]['threshold'] = 0;
                                }
                            }
                            $agents['monitorConfigItem'.$v][$agentk] = $monitorConfigScreen['agent'][$agentk];
                        }
                    }
                    $diffReasonIds = array_diff($reasonIds, $nowReasonIds);
                    foreach ($diffReasonIds as $reasonId) {
                        $agents['monitorConfigItem'.$v]['busy']['busy_data'][$reasonId] = $agent['busy']['busy_data'][$reasonId];
                    }
                    if (!in_array(2, $nowReasonIds) && !empty($nowReasonIds)) {
                        $agents['monitorConfigItem'.$v]['busy']['busy_data'][2] = $agent['busy']['busy_data'][2];
                    }
                } else {
                    $agents['monitorConfigItem'.$v] = $agent;
                }
            }
        } else {
            $configItems = array();

            foreach ($monitorItems as $key => $monitorItmeSource) {
                foreach ($monitorItmeSource as $k => $item) {
                    $i = isset($this->defalurColors[$i]) ? $i : 0;
                    $configItems[$key]['fields'][$k]['text'] = $item['text'];
                    $configItems[$key]['fields'][$k]['checked'] = false;
                }
            }

            $mainFields['monitorConfigItem0'] = $mainField;
            $items['monitorConfigItem0']['id'] = 0;
            $items['monitorConfigItem0']['name'] = $screenMonitor;
            $items['monitorConfigItem0']['refresh'] = '10';
            $items['monitorConfigItem0']['mainFields'] = $configItems;
            $items['monitorConfigItem0']['agent']['is_show'] = false;
            $items['monitorConfigItem0']['agent']['type'] = 1;
            $items['monitorConfigItem0']['agent']['fields'] = $agentFields;

            $agents['monitorConfigItem0'] = $agent;
        }

        return $this->render(
            "IcsocSecurityBundle:Role:roleMonitorConfig.html.twig",
            array(
                'monitorConfigs' => $items,
                'mainFields' => json_encode($mainFields),
                'mainField' => json_encode($mainField),
                'agents' => isset($agents) ? json_encode($agents) : '',
                'agent' => json_encode($agent),
                'phones' => $phones,
                'ifFasreason' => isset($ifFasreason) ? $ifFasreason : false,
                'isEnableGroup' => $isEnableGroup,
                'defautFontColor' => $this->defautFontColor,
                'defautFontSize' => $this->defautFontSize,
                'defautBackground' => $this->defautBackground,
                'defalurColors' => $this->defalurColors,
                'paramsSettingItems' => json_encode($this->paramsSettingItems),
            )
        );
    }

    /**
     * 保存报表配置
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function roleSaveReportAction(Request $request)
    {
        $roleId = $request->get('roleId', '');
        $reportConfig = $request->get('reportConfig', '');
        $reportConfig = json_decode($reportConfig, true);
        $globalReportConfig = $request->get('globalReprotConfig', '');
        $globalReportConfig = json_decode($globalReportConfig, true);
        $globalConfig = $this->processGlobalReportConfig($globalReportConfig);

        $reportItmes = isset($reportConfig['reportItmes']) ? $reportConfig['reportItmes'] : array();
        $calculateItems = isset($reportConfig['calculateItems']) ? $reportConfig['calculateItems'] : array();
        $customItems = isset($reportConfig['customItems']) ? $reportConfig['customItems'] : array();
        $showValues = isset($reportConfig['showValues']) ? $reportConfig['showValues'] : array();

        $config = array();
        foreach ($reportItmes as $key => $reportConfig) {
            $config[$key] = $reportConfig;
            $config[$key]['calculateItems'] = isset($calculateItems[$key]) ? $calculateItems[$key] : '';
            $config[$key]['customItems'] = isset($customItems[$key]) ? $customItems[$key] : '';
            $config[$key]['showValues'] = isset($showValues[$key]) ? $showValues[$key] : '';
        }

        /** 获取所有应用到全局配置的配置项*/
        $realGlobalConfigs = array();
        foreach ($globalConfig as $report => $reportConfig) {
            if (!empty($reportConfig['showValues'])) {
                foreach ($reportConfig['showValues'] as $reportType => $showValues ) {
                    foreach ($showValues as $item => $itemConfig) {
                        if ($itemConfig['globalConfig'] == 1) {
                            $realGlobalConfigs[$report][$reportType][$item] = $itemConfig;
                        }
                    }
                }
            }
        }

        $conn = $this->get('doctrine.dbal.default_connection');
        $lastConfig = $conn->fetchAll("select report_config from cc_roles where role_id = :role_id", array('role_id' => $roleId));
        if (!empty($lastConfig)) {
            $lastConfig = json_decode($lastConfig[0]['report_config'], true);
            if (!empty($lastConfig)) {
                foreach ($lastConfig as $lastReport => $lastReportConfig) {
                    /** 如果没有showValues说明为原来的数据格式，那么要把该角色的原数据格式改成新数据格式，并保持数据信息不变*/
                    if (!isset($lastReportConfig['showValues'])) {
                        $config[$lastReport]['fixed'] = $lastReportConfig['fixed'];
                        $config[$lastReport]['custom'] = $lastReportConfig['custom'];
                        if (!empty($lastReportConfig['customItems'])) {
                            foreach ($lastReportConfig['customItems'] as $customItem => $customItemName) {
                                $config[$lastReport]['customItems']['custom'][$customItem] = $customItemName;
                            }
                        }
                    }
                }
            }
        }

        /** 修改所有角色的应用全局配置，首先获取该企业下的所有角色的配置*/
        $roleConfigs = $conn->fetchAll("select * from cc_roles where vcc_id = :vcc_id and role_id != :role_id", array('vcc_id' => $this->getVccId(), 'role_id' => $roleId));
        $updateRoleConfigs = array();
        foreach ($roleConfigs as $roleConfig) {
            $reportConfig = json_decode($roleConfig['report_config'], true);
            $updateRoleConfigs[$roleConfig['role_id']] = $reportConfig;
            if (!empty($reportConfig)) {
                if (!empty($realGlobalConfigs)) {
                    foreach ($realGlobalConfigs as $report => $realReportConfig) { //report:system,queue,agent,group
                        foreach ($realReportConfig as $reportType => $typeConfig) {//reportType:fixed,custom
                            foreach ($typeConfig as $globalItem => $globalItemConfig) {
                                if (isset($reportConfig[$report]['showValues'])) {
                                    if (empty($reportConfig[$report]['showValues'][$reportType])) {
                                        $reportConfig[$report]['showValues'][$reportType] = $globalConfig[$report]['showValues'][$reportType];
                                    }
                                    /** 若全局配置中有，而本身角色配置中没有，则添加到本身角色配置中*/
                                    if (!in_array($globalItem, array_keys($reportConfig[$report]['showValues'][$reportType]))) {
                                        $updateRoleConfigs[$roleConfig['role_id']][$report][$reportType][] = $globalItem;
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['showValues'][$reportType][$globalItem] = $globalItemConfig;
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['calculateItems'][$globalItem] = $globalConfig[$report]['calculateItems'][$globalItem];
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['customItems'][$reportType][$globalItem] = $globalItemConfig['name'];
                                    }
                                    /** 若全局配置中有，本身角色中也有，则更新配置*/
                                    if (in_array($globalItem, array_keys($reportConfig[$report]['showValues'][$reportType]))) {
                                        //此种情况为自定义指标
                                        if (in_array($globalItem, array_keys($reportConfig[$report]['customItems'][$reportType]))) {
                                            $updateRoleConfigs[$roleConfig['role_id']][$report]['customItems'][$reportType][$globalItem] = $globalItemConfig['name'];
                                        }
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['showValues'][$reportType][$globalItem] = $globalItemConfig;
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['calculateItems'][$globalItem] = $globalConfig[$report]['calculateItems'][$globalItem];
                                    }
                                } else {
                                    /** 将该企业下的其它角色原来的旧数据格式变成新的数据格式*/
                                    $updateRoleConfigs[$roleConfig['role_id']] = array(
                                        'system' => array('fixed' => array(), 'custom' => array(), 'customItems' => array('fixed' => array(),'custom' => array()), 'showValues' => array('fixed' => array(),'custom' => array()), 'calculateItems' => $globalConfig['system']['calculateItems']),
                                        'agent' => array('fixed' => array(), 'custom' => array(), 'customItems' => array('fixed' => array(),'custom' => array()), 'showValues' => array('fixed' => array(),'custom' => array()), 'calculateItems' => $globalConfig['agent']['calculateItems']),
                                        'queue' => array('fixed' => array(), 'custom' => array(), 'customItems' => array('fixed' => array(),'custom' => array()), 'showValues' => array('fixed' => array(),'custom' => array()), 'calculateItems' => $globalConfig['queue']['calculateItems']),
                                        'group' => array('fixed' => array(), 'custom' => array(), 'customItems' => array('fixed' => array(),'custom' => array()), 'showValues' => array('fixed' => array(),'custom' => array()), 'calculateItems' => $globalConfig['group']['calculateItems']));


                                    foreach ($reportConfig as $originReport => $originReportConfig) {
                                        foreach ($originReportConfig['customItems'] as $originItem => $originItemName) {
                                            if ($originItem == 'fixed' || $originItem == 'custom') {
                                                foreach ($originItemName as $k => $v) {
                                                    $updateRoleConfigs[$roleConfig['role_id']][$originReport]['customItems'][$originItem][$k] = $v;
                                                    $updateRoleConfigs[$roleConfig['role_id']][$originReport]['showValues'][$originItem][$k]  = array('name' => $v, 'sort' => 100, 'globalConfig' => 0);
                                                }
                                            } else {
                                                $updateRoleConfigs[$roleConfig['role_id']][$originReport]['customItems']['custom'][$originItem] = $originItemName;
                                                $updateRoleConfigs[$roleConfig['role_id']][$originReport]['showValues']['custom'][$originItem]  = array('name' => $originItemName, 'sort' => 100, 'globalConfig' => 0);

                                            }
                                        }
                                        $updateRoleConfigs[$roleConfig['role_id']][$originReport]['fixed'] = array();
                                        foreach ($originReportConfig['fixed'] as $originItem) {
                                            $updateRoleConfigs[$roleConfig['role_id']][$originReport]['fixed'][] = $originItem;
                                        }
                                        $updateRoleConfigs[$roleConfig['role_id']][$originReport]['custom'] = array();
                                        foreach ($originReportConfig['custom'] as $originItem) {
                                            $updateRoleConfigs[$roleConfig['role_id']][$originReport]['custom'][] = $originItem;
                                        }
                                        foreach ($originReportConfig['calculateItems'] as $originItem => $originItemCofig) {
                                            $updateRoleConfigs[$roleConfig['role_id']][$originReport]['calculateItems'][$originItem] = $originItemCofig;
                                        }
                                    }

                                    //修改的配置是原始配置，而不是自定义配置
                                    if (in_array($globalItem, array_keys($this->reportItems[$report][$reportType.'_report']))) {
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['showValues'][$reportType][$globalItem] = $globalItemConfig;
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['calculateItems'][$globalItem] = $globalConfig[$report]['calculateItems'][$globalItem];
                                    } else {
                                        //为新添加的指标
                                        $updateRoleConfigs[$roleConfig['role_id']][$report][$reportType][] = $globalItem;
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['showValues'][$reportType][$globalItem] = $globalItemConfig;
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['calculateItems'][$globalItem] = $globalConfig[$report]['calculateItems'][$globalItem];
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['customItems'][$reportType][$globalItem] = $globalConfig[$report]['customItems'][$reportType][$globalItem];
                                    }
                                }
                            }
                        }
                    }
                } else {
                    //此种情况为 没有设置为全局修改的配置  但是本身却是旧的数据格式，本身是新的数据格式的除外（没有showValues的就是旧的）
                    if (!isset($reportConfig[$report]['showValues'])) {
                        /** 将该企业下的其它角色原来的旧数据格式变成新的数据格式*/
                        $updateRoleConfigs[$roleConfig['role_id']] = array(
                            'system' => array('fixed' => array(), 'custom' => array(), 'customItems' => array('fixed' => array(),'custom' => array()), 'showValues' => array('fixed' => array(),'custom' => array()), 'calculateItems' => $globalConfig['system']['calculateItems']),
                            'agent' => array('fixed' => array(), 'custom' => array(), 'customItems' => array('fixed' => array(),'custom' => array()), 'showValues' => array('fixed' => array(),'custom' => array()), 'calculateItems' => $globalConfig['agent']['calculateItems']),
                            'queue' => array('fixed' => array(), 'custom' => array(), 'customItems' => array('fixed' => array(),'custom' => array()), 'showValues' => array('fixed' => array(),'custom' => array()), 'calculateItems' => $globalConfig['queue']['calculateItems']),
                            'group' => array('fixed' => array(), 'custom' => array(), 'customItems' => array('fixed' => array(),'custom' => array()), 'showValues' => array('fixed' => array(),'custom' => array()), 'calculateItems' => $globalConfig['group']['calculateItems']));

                        foreach ($reportConfig as $originReport => $originReportConfig) {
                            foreach ($originReportConfig['customItems'] as $originItem => $originItemName) {
                                if (in_array($originItem, array('fixed', 'custom'))) {
                                    foreach ($originItemName as $key => $val) {
                                        $updateRoleConfigs[$roleConfig['role_id']][$originReport]['customItems'][$originItem][$key] = $val;
                                        $updateRoleConfigs[$roleConfig['role_id']][$originReport]['showValues'][$originItem][$key]  = array('name' => $val, 'sort' => 100, 'globalConfig' => 0);
                                    }
                                } else {
                                    $updateRoleConfigs[$roleConfig['role_id']][$originReport]['customItems']['custom'][$originItem] = $originItemName;
                                    $updateRoleConfigs[$roleConfig['role_id']][$originReport]['showValues']['custom'][$originItem]  = array('name' => $originItemName, 'sort' => 100, 'globalConfig' => 0);
                                }
                            }
                            $updateRoleConfigs[$roleConfig['role_id']][$originReport]['fixed'] = array();
                            foreach ($originReportConfig['fixed'] as $originItem) {
                                $updateRoleConfigs[$roleConfig['role_id']][$originReport]['fixed'][] = $originItem;
                            }
                            $updateRoleConfigs[$roleConfig['role_id']][$originReport]['custom'] = array();
                            foreach ($originReportConfig['custom'] as $originItem) {
                                $updateRoleConfigs[$roleConfig['role_id']][$originReport]['custom'][] = $originItem;
                            }
                            if (!empty($originReportConfig['calculateItems'])) {
                                foreach ($originReportConfig['calculateItems'] as $originItem => $originItemCofig) {
                                    $updateRoleConfigs[$roleConfig['role_id']][$originReport]['calculateItems'][$originItem] = $originItemCofig;
                                }
                            }
                        }
                    }
                }

                /** 若全局配置中没有，而本身角色的自定义配置中有，则删除*/
                foreach ($reportConfig as $report => $reportItemConfig) {
                    if (!empty($reportItemConfig['customItems'])) {
                        foreach ($reportItemConfig['customItems'] as $type => $customItemsConfig) {
                            if (in_array($type, array('fixed', 'custom'))) {
                                foreach ($customItemsConfig as $item => $configItem) {
                                    if (isset($globalConfig[$report]['customItems'][$type])) {
                                        if (!in_array($item, array_keys($globalConfig[$report]['customItems'][$type]))) {
                                            foreach($updateRoleConfigs[$roleConfig['role_id']][$report][$type] as $k => $index) {
                                                if ($index == $item) {
                                                    unset($updateRoleConfigs[$roleConfig['role_id']][$report][$type][$k]);
                                                }
                                            }
                                            //unset($updateRoleConfigs[$roleConfig['role_id']][$report][$type][$item]);
                                            unset($updateRoleConfigs[$roleConfig['role_id']][$report]['customItems'][$type][$item]);
                                            unset($updateRoleConfigs[$roleConfig['role_id']][$report]['showValues'][$type][$item]);
                                            unset($updateRoleConfigs[$roleConfig['role_id']][$report]['calculateItems'][$item]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                /** 如果角色本身没有保存报表配置，那么默认取全局配置(即取出所有应用到全局配置的配置项)*/
                $updateRoleConfigs[$roleConfig['role_id']] = $globalConfig;
                foreach ($globalConfig as $report => $globalReportConfig) {
                    if (isset($realGlobalConfigs[$report])) {
                        if (!empty($realGlobalConfigs[$report]['fixed'])) {
                            foreach ($realGlobalConfigs[$report]['fixed'] as $item => $realItemConfig) {
                                if (!in_array($item, $globalReportConfig['fixed'])) {
                                    $updateRoleConfigs[$roleConfig['role_id']][$report]['fixed'][] = $item;
                                }
                                $updateRoleConfigs[$roleConfig['role_id']][$report]['showValues']['fixed'][$item]= $realItemConfig;
                                $updateRoleConfigs[$roleConfig['role_id']][$report]['calculateItems'][$item] = $globalReportConfig['calculateItems'][$item];
                            }
                            foreach ($globalReportConfig['customItems']['fixed'] as $item => $itemConfig) {
                                if (in_array($item, array_keys($realGlobalConfigs[$report]['fixed']))) {
                                    $updateRoleConfigs[$roleConfig['role_id']][$report]['customItems']['fixed'][$item] = $realGlobalConfigs[$report]['fixed'][$item]['name'];
                                }
                            }
                        }

                        if (isset($realGlobalConfigs[$report]['custom'])) {
                            if (!empty($realGlobalConfigs[$report]['custom'])) {
                                foreach ($realGlobalConfigs[$report]['custom'] as $item => $realItemConfig) {
                                    if (!in_array($item, $globalReportConfig['custom'])) {
                                        $updateRoleConfigs[$roleConfig['role_id']][$report]['custom'][] = $item;
                                    }
                                    $updateRoleConfigs[$roleConfig['role_id']][$report]['showValues']['custom'][$item]= $realItemConfig;
                                    $updateRoleConfigs[$roleConfig['role_id']][$report]['calculateItems'][$item] = $globalReportConfig['calculateItems'][$item];
                                }
                            }

                            foreach ($globalReportConfig['customItems']['custom'] as $item => $itemConfig) {
                                if (in_array($item, array_keys($realGlobalConfigs[$report]['custom']))) {
                                    $updateRoleConfigs[$roleConfig['role_id']][$report]['customItems']['custom'][$item] = $realGlobalConfigs[$report]['custom'][$item]['name'];
                                }
                            }
                        }
                    }
                }
            }
        }

        $vccCode = $this->getVccCode();
        $res = $this->container->get('icsoc_data.model.role')->setReportConfig(
            array('vcc_code'=>$vccCode, 'role_id'=>$roleId, 'report_config'=>json_encode($config), 'global_config' => json_encode($globalConfig), 'update_configs' => $updateRoleConfigs)
        );

        return new JsonResponse($res);
    }

    /**
     * 处理全局报表配置
     *
     * @param array $globalConfig
     * @return array
     */
    protected function processGlobalReportConfig($globalConfig)
    {
        $globalReportItems = isset($globalConfig['reportItmes']) ? $globalConfig['reportItmes'] : array();
        $calculateItems = isset($globalConfig['calculateItems']) ? $globalConfig['calculateItems'] : array();
        $customItems = isset($globalConfig['customItems']) ? $globalConfig['customItems'] : array();
        $showValues = isset($globalConfig['showValues']) ? $globalConfig['showValues'] : array();

        $updatItems = array();
        foreach ($showValues as $type => $configs) {
            foreach ($configs as $text => $config) {
                foreach ($config as $item => $v) {
                    $updatItems[$type][$text][$item] = $v;
                }
            }
        }

        $config = array();
        foreach ($globalReportItems as $key => $reportConfig) {
            $config[$key] = $reportConfig;
            $config[$key]['calculateItems'] = isset($calculateItems[$key]) ? $calculateItems[$key] : '';
            $config[$key]['customItems'] = isset($customItems[$key]) ? $customItems[$key] : '' ;
            $config[$key]['showValues'] = isset($updatItems[$key]) ? $updatItems[$key] : '';
        }

        return $config;
    }

    /**
     * 保存监控配置
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function roleSaveMonitorAction(Request $request)
    {
        $roleId = $request->get('roleId', '');
        $monitorInfo = $request->get('monitor_info', '');

        $res = $this->container->get('icsoc_data.model.role')->setMonitorConfig(
            array(
                'vcc_code'=>$this->getVccCode(),
                'role_id'=>$roleId,
                'monitor_info'=>$monitorInfo,
            )
        );

        return new JsonResponse($res);
    }

    /**
     * 添加角色；
     * @param Request $request
     * @return Response
     */
    public function roleAddAction(Request $request)
    {
        $vccCode = $this->getVccCode();
        $name = $request->get('name');
        $roleGrade = $request->get("role_grade");
        $res = $this->container->get('icsoc_data.model.role')->addRole(
            array('vcc_code'=>$vccCode, 'name'=>$name, 'role_grade'=>$roleGrade)
        );

        return new JsonResponse($res);
    }

    /**
     * 编辑用户
     * @param Request $request
     * @return Response
     */
    public function roleEditAction(Request $request)
    {
        $vccCode = $this->getVccCode();
        $name = $request->get('name');
        $roleGrade = $request->get("role_grade");
        $roleId = $request->get("id");
        $res = $this->container->get('icsoc_data.model.role')->editRole(
            array('vcc_code'=>$vccCode, 'name'=>$name, 'role_grade'=>$roleGrade, 'role_id'=>$roleId)
        );

        return new JsonResponse($res);
    }

    /**
     * 获取角色的action_list;
     * @param Request $request
     * @return JsonResponse
     */
    public function roleActionListAction(Request $request)
    {
        $roleId = $request->get("id");
        $vccCode = $this->getVccCode();
        $res = $this->container->get('icsoc_data.model.role')->getRoleList(
            array('vcc_code'=>$vccCode, 'role_id'=>$roleId, 'flag'=>true) //强制需要验证roleId
        );

        return new JsonResponse($res);
    }

    /**
     * 给角色设置 action_list
     * @param Request $request
     * @return JsonResponse
     */
    public function setActionListAction(Request $request)
    {
        $actionList = $request->get('arr_id');
        $roleId = $request->get("id");
        $vccCode = $this->getVccCode();
        $res = $this->container->get('icsoc_data.model.role')->setActionList(
            array('vcc_code'=>$vccCode, 'role_id'=>$roleId, 'action_list'=>$actionList)
        );

        return new JsonResponse($res);
    }

    /**
     * 删除角色
     * @param Request $request
     * @return JsonResponse
     */
    public function deleteRoleAction(Request $request)
    {
        $roleId = (int) $request->get("id");
        $vccCode = $this->getVccCode();
        $res = $this->container->get('icsoc_data.model.role')->delRole(
            array('vcc_code'=>$vccCode, 'role_id'=>$roleId)
        );

        return new JsonResponse($res);
    }

    /**
     * 查询出该坐席的角色类型
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserTypeAction(Request $request)
    {
        $roleId = (int) $request->get("role_id");
        $conn = $this->get("doctrine.dbal.default_connection");

        $reportConfig = $conn->fetchAssoc(
            'SELECT user_type FROM cc_roles WHERE role_id = :role_id',
            array('role_id' => $roleId)
        );

        if (!in_array($reportConfig['user_type'], array(0, 1, 3))) {
            return new JsonResponse(
                array(
                    'code' => 400,
                    'msg' => '无权限操作大屏监控',
                )
            );
        } else {
            return new JsonResponse(
                array(
                    'code' => 200,
                    'msg' => 'ok',
                )
            );
        }
    }

    /**
     * 复制角色
     *
     * @param Request $request
     */
    public function copyRoleAction(Request $request)
    {
        $vccId = $this->getVccId();
        $roleId = $request->get('roleId');
        $name = $request->get('name');
        $param['roleId'] = $roleId;
        $param['name'] = $name;
        $param['vccId'] = $vccId;
        $param['vccCode'] = $this->getVccCode();
        $res = $this->container->get('icsoc_data.model.role')->setCopyRole($param);

        return new JsonResponse($res);
    }
}
